package com.example.pcbcsmbackend.controller;

import com.example.pcbcsmbackend.entity.Product;
import com.example.pcbcsmbackend.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/product")
@CrossOrigin(origins = {"http://localhost:8080", "http://localhost:8081"})
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    // 获取所有商品
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllProducts() {
        Map<String, Object> response = new HashMap<>();
        List<Product> products = productService.getAllProducts();
        response.put("success", true);
        response.put("products", products);
        return ResponseEntity.ok(response);
    }
    
    // 分页获取商品
    @GetMapping("/page")
    public ResponseEntity<Map<String, Object>> getProductsByPage(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> response = new HashMap<>();
        Page<Product> productPage = productService.getProductsByPage(page, size);
        response.put("success", true);
        response.put("products", productPage.getContent());
        response.put("totalElements", productPage.getTotalElements());
        response.put("totalPages", productPage.getTotalPages());
        response.put("currentPage", page);
        return ResponseEntity.ok(response);
    }
    
    // 根据ID获取商品详情
    @GetMapping("/{productId}")
    public ResponseEntity<Map<String, Object>> getProductById(@PathVariable Integer productId) {
        Map<String, Object> response = new HashMap<>();
        Optional<Product> product = productService.findById(productId);
        if (product.isPresent()) {
            response.put("success", true);
            response.put("product", product.get());
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "商品不存在");
            return ResponseEntity.ok(response);
        }
    }
    
    // 根据分类获取商品
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<Map<String, Object>> getProductsByCategory(@PathVariable Integer categoryId) {
        Map<String, Object> response = new HashMap<>();
        List<Product> products = productService.getProductsByCategory(categoryId);
        response.put("success", true);
        response.put("products", products);
        return ResponseEntity.ok(response);
    }
    
    // 搜索商品
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchProducts(@RequestParam String keyword) {
        Map<String, Object> response = new HashMap<>();
        List<Product> products = productService.searchProducts(keyword);
        response.put("success", true);
        response.put("products", products);
        return ResponseEntity.ok(response);
    }
    
    // 获取热门商品
    @GetMapping("/hot")
    public ResponseEntity<Map<String, Object>> getHotProducts() {
        Map<String, Object> response = new HashMap<>();
        List<Product> products = productService.getHotProducts();
        response.put("success", true);
        response.put("products", products);
        return ResponseEntity.ok(response);
    }
    
    // 添加商品（管理员功能）
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addProduct(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String productName = (String) request.get("productName");
            String specParams = (String) request.get("specParams");
            BigDecimal price = new BigDecimal(request.get("price").toString());
            Integer stock = Integer.parseInt(request.get("stock").toString());
            String productImage = (String) request.get("productImage");
            Integer categoryId = Integer.parseInt(request.get("categoryId").toString());
            String description = (String) request.get("description");
            
            Product product = productService.addProduct(productName, specParams, price, 
                                                       stock, productImage, categoryId, description);
            response.put("success", true);
            response.put("message", "商品添加成功");
            response.put("product", product);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 更新商品（管理员功能）
    @PutMapping("/update/{productId}")
    public ResponseEntity<Map<String, Object>> updateProduct(@PathVariable Integer productId, @RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 先查找现有商品
            Optional<Product> existingProductOpt = productService.findById(productId);
            if (!existingProductOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "商品不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            Product product = existingProductOpt.get();
            
            // 更新商品信息
            if (request.get("productName") != null) {
                product.setProductName((String) request.get("productName"));
            }
            if (request.get("specParams") != null) {
                product.setSpecParams((String) request.get("specParams"));
            }
            if (request.get("price") != null) {
                product.setPrice(new BigDecimal(request.get("price").toString()));
            }
            if (request.get("stock") != null) {
                product.setStock(Integer.parseInt(request.get("stock").toString()));
            }
            if (request.get("productImage") != null) {
                product.setProductImage((String) request.get("productImage"));
            }
            if (request.get("categoryId") != null) {
                product.setCategoryId(Integer.parseInt(request.get("categoryId").toString()));
            }
            if (request.get("description") != null) {
                product.setDescription((String) request.get("description"));
            }
            
            Product updatedProduct = productService.updateProduct(product);
            response.put("success", true);
            response.put("message", "商品更新成功");
            response.put("product", updatedProduct);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 删除商品（管理员功能）
    @DeleteMapping("/{productId}")
    public ResponseEntity<Map<String, Object>> deleteProduct(@PathVariable Integer productId) {
        Map<String, Object> response = new HashMap<>();
        try {
            productService.deleteProduct(productId);
            response.put("success", true);
            response.put("message", "商品删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    // 批量删除商品（管理员功能）
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteProducts(@RequestBody List<Integer> productIds) {
        Map<String, Object> response = new HashMap<>();
        try {
            productService.batchDeleteProducts(productIds);
            response.put("success", true);
            response.put("message", "批量删除商品成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 